package info.nixbear.tgcms.services.dao.appengine;

import info.nixbear.tgcms.domain.Attachment;
import info.nixbear.tgcms.services.dao.AttachmentDao;
import info.nixbear.tgcms.services.dao.PMF;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppengineAttachmentDao extends AppengineEntityDao<Attachment> implements AttachmentDao {

	Logger logger = LoggerFactory.getLogger(AppengineAttachmentDao.class);

	public AppengineAttachmentDao() {
		super(Attachment.class);
	}

	@Override
	public Attachment findByUrl(String url) {
		if (url == null) {
			return null;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.getFetchPlan().addGroup("all");
		pm.setDetachAllOnCommit(true);

		Attachment attachment = null;
		
		try {

			Query query = pm.newQuery("select from " + Attachment.class.getName()
					+ " where url == urlParam " + " parameters String urlParam ");

			@SuppressWarnings("unchecked")
			List<Attachment> pages = (List<Attachment>) query.execute(url);

			attachment = (pages == null || pages.size() == 0) ? null : pages.get(0);

			attachment = pm.detachCopy(attachment);
		} finally {
			pm.close();
		}

		return attachment;
	}
	
}
